from os.path import join as pathjoin, isdir
from os import makedirs
from configparser import ConfigParser
from utils.logger import Logger
from datetime import datetime, timedelta

cfg_file = f'./cfg/config.ini'
config = ConfigParser()
config.read(cfg_file)

Tem_max = config.getfloat('default', 'TMAX')
Tem_min = config.getfloat('default', 'TMIN')
C_K = 273.15

cus_time = config['default'].get('custom version date')
test_days = config['default'].getint('test days')
if cus_time is not None:
    currentTime = datetime.strptime(cus_time[:8].ljust(14, '0'), '%Y%m%d%H%M%S')
elif test_days is not None:
    currentTime = datetime.now() - timedelta(days=int(test_days))
else:
    currentTime = datetime.now()

# logpath = config.get('default', 'logpath')
logpath = 'log'
if not isdir(logpath):
    makedirs(logpath)

cfg_logger = Logger(filename=f'{logpath}/config.log', level='info', when='D', back_count=1).logger

scmoc_Micaps_path = config['train data'].get('scmoc_micaps_path')
if scmoc_Micaps_path is not None and not isdir(scmoc_Micaps_path):
    cfg_logger.error(f'{scmoc_Micaps_path} does not exist!')

scmoc_grib2_path = config['train data'].get('scmoc_grib2_path')
if scmoc_grib2_path is not None and not isdir(scmoc_grib2_path):
    cfg_logger.error(f'{scmoc_grib2_path} does not exist!')

cldas_grib2_path = config['train data']['cldas_grib2_path']
if cldas_grib2_path is not None and not isdir(cldas_grib2_path):
    cfg_logger.error(f'{cldas_grib2_path} does not exist!')

station_micaps_path = config['train data']['station_micaps_path']

station_ids_file = config['train data']['station_ids_file']
station_headline = config['train data'].getint('station_headline')
National_station_ids = open(station_ids_file).readlines()
National_station_ids = [idx.strip() for idx in National_station_ids]

revise_cldas = config.getboolean('train data', 'revise_cldas')
if revise_cldas:
    assert isdir(station_micaps_path), f'station_micaps_path:{station_micaps_path} does not exist!'
revise_points = config['train data'].getint('revise_points')

datasets_root = config['train data']['datasets_root']
assert isdir(datasets_root), f'datasets_root:{datasets_root} does not exist!'

scmoc_npy_path = pathjoin(datasets_root, 'scmoc')

cldas_npy_path = pathjoin(datasets_root, 'cldas')

txt_path = pathjoin(datasets_root, 'txtsets')

weight_root = config['train data']['weight_root']

# 订正网络进程持续时间(s)
process_duration = config['revise info'].getint('revise_duration')

scmoc_new_path = config['revise info']['scmoc_new_path']
if not isdir(scmoc_new_path):
    cfg_logger.warning("Please make sure the scmoc_new_path is correct!")
    makedirs(scmoc_new_path)

scmoc_backup_path = config['revise info']['scmoc_backup_path']

scmoc_issue_path = config['revise info']['scmoc_issue_path']

revise_out_path = config['revise info']['revise_out_path']

revise_out12_path = config['revise info']['revise_out12_path']

revise_out_history_path = config['revise info']['revise_out_history_path']

revise_out12_history_path = config['revise info']['revise_out12_history_path']

bc_out_path = config['revise info'].get("bc_out_path")

bc_out12_path = config['revise info']['bc_out12_path']

bc_hsteps = config['revise info'].getint('bc_hsteps')

bc_days = config['revise info'].getint('bc_days')

revise_issue_path = config['revise info']['revise_issue_path']

offset = 0.001
latmin = config.getfloat('data info', 'latmin') - offset
latmax = config.getfloat('data info', 'latmax') + offset
lonmin = config.getfloat('data info', 'lonmin') - offset
lonmax = config.getfloat('data info', 'lonmax') + offset

stepStart = config.getint('data info', 'stepStart')
stepEnd = config.getint('data info', 'stepEnd')
hourStride = config.getint('data info', 'hourStride')

grid = config.getfloat('data info', 'grid')
datadays = config.getint('data info', 'datadays')

valrate = int(config['data info']['valrate'].split('/')[0]) / int(config['data info']['valrate'].split('/')[1])

valdays = config.getint('data info', 'valdays')

area_width = round((latmax - latmin) / grid + 1)
area_height = round((lonmax - lonmin) / grid + 1)

width = (area_width - area_width % 8)
height = (area_height - area_height % 8)

device = config.get('model info', 'device')

initTrain = config.getboolean('model info', 'init_train')

leaning_rate = config.getfloat('model info', 'leaning_rate')

weight_decay = config.getfloat('model info', 'weight_decay')

Tcategorys = [tc.strip().upper() for tc in config['model info']['Tcategorys'].split(',')]

htimes = [hc.strip() for hc in config['model info']['htimes'].split(',')]

gpu_ids = config['model info'].get('device_ids')
if gpu_ids is None:
    device_ids = [0]
else:
    device_ids = [int(idx.strip()) for idx in gpu_ids.split(',')]

batch_size = config.getint('model info', 'batch_size')

core_count = config.getint('model info', 'core_count')

thread_count = config.getint('model info', 'thread_count')

maxepoch = config.getint('model info', 'maxepoch')
if initTrain:
    maxepoch += 100
auto_update = config['model info'].getboolean('auto update')
last_train_date = config.get('model info', 'last_train_date')

for _tcls in Tcategorys:
    for basefolder in [scmoc_npy_path, cldas_npy_path, txt_path, weight_root, scmoc_new_path, scmoc_backup_path,
                       scmoc_issue_path, revise_out_path, revise_out12_path, revise_out_history_path,
                       revise_out12_history_path, bc_out_path,
                       bc_out12_path]:
        tfolder = pathjoin(basefolder, _tcls)
        if not isdir(tfolder):
            cfg_logger.info(f"MAKEING DIR:{tfolder}")
            makedirs(tfolder)
